package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.AuthUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.auth.LoginType;
import com.ruoyi.framework.shiro.auth.UserToken;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.system.domain.SysAuthUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 第三方认证授权处理
 *
 * @author ruoyi
 */
@Controller
public class SysAuthController extends BaseController {
    private AuthStateCache authStateCache;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

//    @Autowired(required = false)
//    private ChromeDriver driver;

    private final static Map<String, String> auths = new HashMap<String, String>();

    {
        auths.put("gitee", "{\"clientId\":\"e5cf90f79b02128d8f140d6898c480ea9dc5278e15a23617e38b58de8ebdc8be\",\"clientSecret\":\"c02d1df684909ba465cf521d94209e2a50e45f2199244f2af697b514efb38d60\",\"redirectUri\":\"http://127.0.0.1:80/auth/callback/gitee\"}");
        auths.put("github", "{\"clientId\":\"Iv1.1be0cdcd71aca63b\",\"clientSecret\":\"0d59d28b43152bc8906011624db37b0fed88d154\", \"redirectUri\":\"http://127.0.0.1:80/auth/callback/github\"}");
        authStateCache = AuthDefaultStateCache.INSTANCE;
    }



    /**
     * 认证授权
     *
     * @param source
     * @throws IOException
     */
    @GetMapping("/auth/{source}")
    @ResponseBody
    public void renderAuth(@PathVariable("source") String source) throws IOException {
        String options = auths.get(source);
        if (StringUtils.isEmpty(options)) {
            return;
        }
        JSONObject json = JSONObject.parseObject(options);
        AuthRequest authRequest = AuthUtils.getAuthRequest(source, json.getString("clientId"), json.getString("clientSecret"), URLEncoder.encode(json.getString("redirectUri")), authStateCache);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        logger.debug("authorizeUrl: {}", authorizeUrl);
        ServletUtils.getResponse().sendRedirect(authorizeUrl);
    }


    /**
     * 回调结果
     */
    @SuppressWarnings("unchecked")
    @GetMapping("/auth/callback/{source}")
    public Object callbackAuth(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request) {
        String obj = auths.get(source);
        if (StringUtils.isEmpty(obj)) {
            return new ModelAndView("error/unauth");
        }

        JSONObject json = JSONObject.parseObject(obj);
        AuthRequest authRequest = AuthUtils.getAuthRequest(source, json.getString("clientId"),//
                json.getString("clientSecret"), json.getString("redirectUri"), authStateCache);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        if (response.ok()) {
            if (SecurityUtils.getSubject() != null && SecurityUtils.getSubject().getPrincipal() != null) {
                SysUser user = userMapper.selectAuthUserByUuid(source + response.getData().getUuid());
                if (StringUtils.isNotNull(user)) {
                    return redirect("/index");
                }
                // 若已经登录则直接绑定系统账号
                SysAuthUser authUser = new SysAuthUser();
                authUser.setAvatar(response.getData().getAvatar());
                authUser.setUuid(source + response.getData().getUuid());
                authUser.setUserId(ShiroUtils.getUserId());
                authUser.setUserName(response.getData().getNickname());
                authUser.setLoginName(response.getData().getUsername());
                authUser.setEmail(response.getData().getEmail());
                authUser.setSource(source);
                userMapper.insertAuthUser(authUser);
                return redirect("/index");
            }
            SysUser user = userMapper.selectAuthUserByUuid(source + response.getData().getUuid());
            if (StringUtils.isNotNull(user)) {
                Subject subject = SecurityUtils.getSubject();
                UserToken token = new UserToken(user.getLoginName(), LoginType.NOPASSWD);
                subject.login(token);
                return redirect("/index");
            } else {
                SysAuthUser authUser = new SysAuthUser();
                authUser.setAvatar(response.getData().getAvatar());
                authUser.setUuid(source + response.getData().getUuid());
//                authUser.setUserId(ShiroUtils.getUserId());
                authUser.setUserName(response.getData().getNickname());
                authUser.setLoginName(response.getData().getUsername() + System.nanoTime());
                authUser.setEmail(response.getData().getEmail());
                authUser.setPhonenumber(response.getData().getRawUserInfo().getString("phonenumber"));
                authUser.setSource(source);
//                userMapper.insertAuthUser(authUser);
                // insert sysuser
                SysUser sysUser = new SysUser();
                // 判断是否是之前的 login_name, email, phonenumber
                sysUser.setUserName(authUser.getUserName());
                sysUser.setPhonenumber(authUser.getPhonenumber());
                sysUser.setLoginName(authUser.getLoginName());
                sysUser.setEmail(authUser.getEmail());
                sysUser.setSalt(ShiroUtils.randomSalt());
                sysUser.setPassword(configService.getKey("sys.user.initPassword"));
                sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt()));
                if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && userService.checkPhoneUnique(sysUser)) {
                    sysUser = userMapper.checkPhoneUnique(String.valueOf(sysUser));
                } else if (StringUtils.isNotEmpty(sysUser.getEmail()) && userService.checkEmailUnique(sysUser)) {
                    sysUser = userMapper.checkEmailUnique(String.valueOf(sysUser));
                } else {
                    userService.insertUser(sysUser);
                    sysUser = userService.selectUserById(sysUser.getUserId());
                }
                authUser.setUserId(sysUser.getUserId());
                userMapper.insertAuthUser(authUser);
                Subject subject = SecurityUtils.getSubject();
                UserToken token = new UserToken(sysUser.getLoginName(), LoginType.NOPASSWD);
                subject.login(token);
                return redirect("/index");
//                return new ModelAndView("error/bind");
            }
        }
        return new ModelAndView("error/404");
    }

    /**
     * 检查是否授权
     */
    @PostMapping("/auth/checkAuthUser")
    @ResponseBody
    public AjaxResult checkAuthUser(SysAuthUser authUser) {
        Long userId = ShiroUtils.getUserId();
        String source = authUser.getSource();
        if (userMapper.checkAuthUser(userId, source) > 0) {
            return error(source + "平台账号已经绑定");
        }
        return AjaxResult.success();
    }

    /**
     * 取消授权
     */
    @PostMapping("/auth/unlock")
    @ResponseBody
    public AjaxResult unlockAuth(SysAuthUser authUser) {
        return toAjax(userMapper.deleteAuthUser(authUser.getAuthId()));
    }


//    @GetMapping("/auth/wxlogin")
//    public String wechatLogin() throws IOException {
//        return "wxlogin";
//    }
//    @GetMapping("/auth/wx/check-login-status")
//    @ResponseBody
//    public AjaxResult checkLoginStatus() {
//        // 简单模拟判断是否登录成功（实际需准确判断微信登录后的页面变化等情况）
////        if (driver != null && driver.getTitle().contains("微信登录成功后的相关标识")) {
////            return AjaxResult.success();
////        }
//        return AjaxResult.error("登录失败");
//    }

//    @GetMapping("/auth/wxlogin/index")
//    public String wechatLoginAfterLoginPage() {
//        // 从微信网页版登录成功后的页面URL中获取授权码（真实应用需按照微信回调逻辑准确处理）
////        String currentUrl = driver.getCurrentUrl();
//        String authorizationCode = extractAuthorizationCode("currentUrl");
//
//        // 准备向微信开放平台换取access_token的请求URL（这里的URL等参数是示例，实际要按照微信文档配置）
//        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
//        Map<String, String> tokenParams = new HashMap<>();
////        tokenParams.put("appid", "你的AppID");
////        tokenParams.put("secret", "你的AppSecret");
//        tokenParams.put("appid", "wx625332d25a3005b7");
//        tokenParams.put("secret", "172c7e47a28bab2b72554a5f80bf5259");
//        tokenParams.put("code", authorizationCode);
//        tokenParams.put("grant_type", "authorization_code");
//
//        RestTemplate restTemplate = new RestTemplate();
//        // 发送请求获取access_token
//        ResponseEntity<Map> tokenResponse = restTemplate.exchange(tokenUrl, HttpMethod.POST, new HttpEntity<>(tokenParams), Map.class);
//        Map<String, Object> tokenInfo = tokenResponse.getBody();
//        if (tokenInfo == null || !tokenInfo.containsKey("access_token")) {
//            // 如果获取access_token失败，返回错误信息或者进行相应处理（这里简单返回空信息示例）
////            return new HashMap<>();
//            return "";
//        }
//
//        // 从获取到的信息中提取access_token
//        String accessToken = (String) tokenInfo.get("access_token");
//
//        // 准备获取用户信息的请求URL
//        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo";
//        Map<String, String> userInfoParams = new HashMap<>();
//        userInfoParams.put("access_token", accessToken);
//        userInfoParams.put("openid", (String) tokenInfo.get("openid"));
//
//        // 发送请求获取用户信息
//        ResponseEntity<Map> userInfoResponse = restTemplate.exchange(userInfoUrl, HttpMethod.GET, new HttpEntity<>(userInfoParams), Map.class);
//        logger.debug("userInfo: {}", JSON.toJSONString(userInfoResponse));
////        return userInfoResponse.getBody();
//        return "<html><body><h1>微信登录成功，欢迎来到系统页面！</h1></body></html>";
//    }
//private String extractAuthorizationCode(String url) {
//    // 定义正则表达式模式，用于匹配URL中授权码的参数部分（示例，可根据微信实际回调URL格式调整）
//    Pattern pattern = Pattern.compile("code=(.*?)&");
//    Matcher matcher = pattern.matcher(url);
//    if (matcher.find()) {
//        return matcher.group(1);
//    }
//    return null;
//}

}
